/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Threading;
using System.Collections.Generic;
using Whitemice.ZOGI;
using log4net;

[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension="log4net",Watch=true)]
namespace Whitemice.OGoMojo.OGoNotify
{
	class OGoNotify
	{	  
	  private static readonly ILog log = LogManager.GetLogger(typeof(OGoNotify));
    protected IList<Whitemice.ZOGI.Entity>  results;
    protected bool                          run;
    protected XMPPServer                    xmppServer;
    protected SMTPServer                    smtpServer;
    protected INIConfiguration              ini;
	  
    [STAThread]
		public static void Main(string[] args)
		{     
		  new OGoNotify().Run();
		}
		
		public OGoNotify()
		{
		  ini = new INIConfiguration();
		  xmppServer = new XMPPServer(
		    ini.GetDirectiveValue("OGoNotify", "XMPPServer"), 
		    5222, 
		    "OGoMojo", 
		    ini.GetDirectiveValue("OGoNotify", "XMPPRealm"));
		  xmppServer.Login(
		    ini.GetDirectiveValue("OGoNotify", "XMPPUser"),
		    ini.GetDirectiveValue("OGoNotify", "XMPPSecret"));
		  smtpServer = new SMTPServer(
		    ini.GetDirectiveValue("OGoNotify", "SMTPServer"), 
		    ini.GetDirectiveValue("OGoNotify", "SMTPUser"), 
		    ini.GetDirectiveValue("OGoNotify", "SMTPSecret"),
		    false);
		  ZOGIApplication.Init();
      //ZOGIApplication.Server.OnServerEvent += new zOGIServerEventHandler(EnqueueEvent);
      ZOGIApplication.Server.OnException += new zOGIExceptionHandler(ExceptionEvent);
      ZOGIApplication.Server.Establish(
        ini.GetDirectiveValue("OGoNotify", "OGoHost"),
        ini.GetDirectiveValue("OGoNotify", "OGoUser"),
        ini.GetDirectiveValue("OGoNotify", "OGoSecret"));
      if (ZOGIApplication.Server.Established && xmppServer.ReadyToSend && smtpServer.ReadyToSend)
      {
        run = true;
        log.Info("Established connection to OGo server.");
      } else 
        {
          run = false;
          log.Info("Unable to established connection to OGo server.");
        }
    }
    
		protected void EnqueueEvent(ServerEvent _event)
		{
      /* Do nothing, this app doesn't care */
		} /* end EnqueueEvent */    
		
		protected void ExceptionEvent(Exception _exception, int _faultCode, string _faultString)
		{
		  run = false;
		  log.ErrorFormat("Fault#{0} Error:{1}\nException: {2}\n{3}",
		    _faultCode,
		    _faultString,
		    _exception.Message, 
		    _exception.StackTrace);
		}
    
    public void Run()
    {
      DateTime  start;
      DateTime  end;
      Entity    target, source;
      string    message;
      
      while (run)
      {
        Thread.Sleep(150000);
        start = DateTime.Now.AddHours(-12.0);
        end = DateTime.Now.AddDays(10.0);
        results = ZOGIApplication.Server.GetNotifications(start, end);
        foreach(Notification notification in results)
        {
          target = ZOGIApplication.Server.Get(notification.TargetObjectId, 0);
          source = ZOGIApplication.Server.Get(notification.SourceObjectId, 65535);          
          switch (notification.SourceEntityName)
          {
            case "Appointment":
              
              log.InfoFormat("Notification requested to {0} for appointmentId#{1}",
                              target,
                              notification.SourceObjectId);
              message = RenderMessage(notification, (source as Appointment));
              switch (target.EntityName)
              {
                case "Contact":
                  /* Notification is to a contact */
                  if ((target as Contact).IsAccount)
                  {
                    /* Notification is to a user, always send */
                    if (notification.IMAddress.Length > 0)
                    {
                      /* Send IM notification! */
                      xmppServer.Send(notification.IMAddress, 
                                      string.Format("Appointment Reminder\n{0}", message));
                    }
                    if (notification.EMails.Count > 0)
                    {
                      /* Send SMTP notification */
                      smtpServer.Send(notification.EMails, "Appointment Reminder", message);
                    }
                    
                  }
                  break;
                case "Team":
                  /* Notification is to a team */
                  break;
              }
              break;
            case "Task":
              break;
          }
        }
      }
      Shutdown();
    }
    
    public void Shutdown()
    {
      ZOGIApplication.Shutdown();
    }
    
    public string RenderMessage(Notification _notification, Appointment _appointment)
    {
      string message;
      DateTime start, end;
      
      start = _appointment.Start.AddSeconds(_notification.StartOffset);
      end = _appointment.End.AddSeconds(_notification.EndOffset);
      
      message = string.Empty;
      message += string.Format("Title: {0}\n",  _appointment.Title);
      message += string.Format("Time: {0}{1} - {2}{3}\n", 
                  start.ToString("yyyy-MM-dd HH:mm"),
                  _notification.StartTimeZone,
                  end.ToString("yyyy-MM-dd HH:mm"),
                  _notification.EndTimeZone);      
      message += string.Format("Location: {0}\n", _appointment.Location);
      message += string.Format("Type: {0}\n", _appointment.AppointmentType);
      message += string.Format("Comment: {0}\n\n", _appointment.Comment);
      message += string.Format("Id#{0}\n", _appointment.ObjectId.ToString());
      return message;
    }
  }
}